/**
 * 前序递归遍历，交换每个节点的左右子节点
 * @param {TreeNode} root
 * @return {TreeNode}
 */

const reverse = node => {
  const temp = node.left
  node.left = node.right
  node.right = temp
}

const invertTree = root => {
  const inverNode = node => {
    if (!node) return root
    reverse(node)
    if (node.left) inverNode(node.left)
    if (node.right) inverNode(node.right)
  }
  inverNode(root)
  return root
}

const root = {
  val: 1,
  left: {
    val: 2,
    left: null,
    right: null
  },
  right: {
    val: 3,
    left: null,
    right: null
  }
}

console.log(invertTree(root))